from apps.meiduo_admin.utils import PageNum
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import Brand
from apps.meiduo_admin.serializers.brand import BrandSerializer
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response


class BrandModelViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        image = request.FILES.get('logo')

        client = Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')
        res = client.upload_appender_by_buffer(image.read())

        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']

        brand = Brand.objects.create(name=name, first_letter=first_letter, logo=image_url)
        return Response({
            "id": brand.id,
            "name": brand.name,
            "logo": brand.logo.url,
            "first_letter": brand.first_letter
        }, status=201)

    def update(self, request, *args, **kwargs):
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        image = request.FILES.get('logo')

        old_brand = self.get_object()  # 通过pk获取到需要修改的该对象

        client = Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')
        res = client.upload_appender_by_buffer(image.read())

        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']

        old_brand.name = name
        old_brand.first_letter = first_letter
        old_brand.logo = image_url
        old_brand.save()

        return Response({
            "id": old_brand.id,
            "name": old_brand.name,
            "logo": old_brand.logo.url,
            "first_letter": old_brand.first_letter
        }, status=201)
